package org.jeecg.modules.mq.config;

import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.mq.constant.RabbitConstants;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
@Slf4j
public class RabbitConfig {
    @Autowired
    private CachingConnectionFactory connectionFactory;

    @Bean
    public RabbitTemplate createRabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate rabbitTemplate = new RabbitTemplate();
        rabbitTemplate.setConnectionFactory(connectionFactory);
        //设置开启Mandatory,才能触发回调函数,无论消息推送结果怎么样都强制调用回调函数
        rabbitTemplate.setMandatory(true);
        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            @Override
            public void confirm(CorrelationData correlationData, boolean ack, String cause) {
                if (ack) {
                    log.info("ConfirmCallback:     " + "相关数据：{},确认情况：{},原因：{}",correlationData,ack,cause);
                } else {
                    log.info("ConfirmCallback:     " + "相关数据：{},确认情况：{},原因：{}",correlationData,ack,cause);
                }
            }
        });
        /*消息从Exchange路由到Queue失败的回调*/
        rabbitTemplate.setReturnsCallback(new RabbitTemplate.ReturnsCallback() {
            @Override
            public void returnedMessage(ReturnedMessage returnedMessage) {
                log.info("ReturnCallback:     " + "消息：{},回应码：{},回应信息：{},交换机：{},路由键：{}",returnedMessage.getMessage(),
                        returnedMessage.getReplyCode(), returnedMessage.getReplyText(), returnedMessage.getExchange(), returnedMessage.getRoutingKey());
            }
        });
        return rabbitTemplate;
    }

    /**
     * 确认消费模式为手动确认机制-MANUAL,采用直连传输directExchange消息模型
     */
    @Bean
    public SimpleRabbitListenerContainerFactory singleListenerContainerManual() {
        //定义消息监听器所在的容器工厂
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        //设置容器工厂所用的实例
        factory.setConnectionFactory(connectionFactory);
        //设置消息在传输中的格式，在这里采用JSON的格式进行传输
//        factory.setMessageConverter(new Jackson2JsonMessageConverter());
        //设置并发消费者实例的初始数量。在这里为1个
        factory.setConcurrentConsumers(1);
        //设置并发消费者实例的最大数量。在这里为1个
        factory.setMaxConcurrentConsumers(3);
        //设置并发消费者实例中每个实例拉取的消息数量-在这里为1个
        factory.setPrefetchCount(1);
        //确认消费模式为自动确认机制
        factory.setAcknowledgeMode(AcknowledgeMode.MANUAL);
        return factory;
    }

    //正常队列
    @Bean
    public Queue orderQueue() {
        Map<String, Object> args = new HashMap<>(3);
        //声明当前队列绑定的死信交换机
        args.put("x-dead-letter-exchange", RabbitConstants.ORDER_DLX_EXCHANGE);
        //声明当前队列的死信路由 key
        args.put("x-dead-letter-routing-key", "dead.info");
        args.put("x-max-length", 10);
        //参数介绍
        //1.队列名 2.是否持久化 3.是否独占 4.自动删除 5.其他参数
        return new Queue(RabbitConstants.ORDER_QUEUE, true, false, false, args);
    }
    //正常交换机
    @Bean
    TopicExchange OrderExchange() {
        //参数介绍
        //1.交换器名 2.是否持久化 3.自动删除 4.其他参数
        return new TopicExchange(RabbitConstants.ORDER_EXCHANGE, true, false, null);
    }

    //正常交换机路由绑定正常队列
    @Bean
    Binding bindingExchangeMessage() {
        return BindingBuilder.bind(orderQueue()).to(OrderExchange()).with("order.#");
    }

    //死信队列
    @Bean
    public Queue deadOrderQueue() {
        return new Queue(RabbitConstants.ORDER_DLX_QUEUE, true, false, false, null);
    }

    //死信交换机
    @Bean
    public TopicExchange deadOrderExchange() {
        return new TopicExchange(RabbitConstants.ORDER_DLX_EXCHANGE, true, false, null);
    }

    //死信交换机路由绑定死信队列
    @Bean
    public Binding deadBinding() {
        return BindingBuilder.bind(deadOrderQueue()).to(deadOrderExchange()).with("dead.#");
    }


}
